<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关键词" prop="cond">
        <el-input v-model="queryParams.cond" placeholder="请输入关键词搜索" ref="cond" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" class="search-btn" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" class="reset-btn" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" class="action-button add-btn" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" icon="el-icon-sort" size="mini" class="action-button expand-btn" @click="toggleExpandAll">{{ isExpandAll ? '折叠' : '展开' }}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="indicatorList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      class="tree-table"
      :row-class-name="rowClassName">
      <el-table-column label="名称" prop="name" min-width="100">
        <template slot-scope="scope">
          <span class="tree-node-name">
            <i :class="scope.row.isdir === 'Y' ? 'el-icon-folder' : 'el-icon-document'" class="node-icon"></i>
            {{ scope.row.name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="编码" align="left" prop="code" min-width="50"/>
      <el-table-column label="需求类型" align="center" min-width="50">
        <template slot-scope="scope">
          <span v-if="scope.row.isdir === 'Y'">-</span>
          <el-tag v-else-if="scope.row.type === 'text'" type="success" size="mini">文本</el-tag>
          <el-tag v-else-if="scope.row.type === 'num'" type="primary" size="mini">数字</el-tag>
          <el-tag v-else-if="scope.row.type === 'option'" type="info" size="mini">选项</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="100" class-name="small-padding fixed-width operation-column">
        <template slot-scope="scope">
          <div class="table-operation">
            <a href="javascript:;" class="link-text edit-link" @click="handleUpdate(scope.row)">
              <i class="el-icon-edit"></i>修改
            </a>
            <span class="link-divider">|</span>
            <template v-if="scope.row.isdir === 'Y'">
              <a href="javascript:;" class="link-text add-link" @click="handleAdd(scope.row)">
                <i class="el-icon-plus"></i>新增
              </a>
            </template>
            <template v-else>
              <span class="empty-placeholder"></span>
            </template>
            <span class="link-divider">|</span>
            <a href="javascript:;" class="link-text delete-link" @click="handleDelete(scope.row)">
              <i class="el-icon-delete"></i>删除
            </a>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body class="ind-dialog" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" @keyup.ctrl.enter.native="submitForm" class="ind-form">
        <el-form-item label="上级结构" prop="pid" class="form-item">
          <treeselect v-model="form.pid"
                     :options="indicatorOptions"
                     :normalizer="normalizer"
                     :isDisabled="node => node.isdir === 'N'"
                     placeholder="请选择上级结构"
                     class="tree-select"/>
        </el-form-item>
        <el-form-item label="编码" prop="code" class="form-item">
          <el-input v-model="form.code" ref="code" placeholder="请输入编码" class="form-input"/>
        </el-form-item>
        <el-form-item label="名称" prop="name" class="form-item">
          <el-input v-model="form.name" placeholder="请输入名称" class="form-input"/>
        </el-form-item>
        <el-form-item label="是否为目录" prop="isdir" class="form-item">
          <el-radio-group v-model="form.isdir" @change="handleIsdirChange" class="form-radio-group">
            <el-radio label="Y">是</el-radio>
            <el-radio label="N">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.isdir === 'N'" label="需求类型" prop="type" class="form-item type-selector">
          <el-radio-group v-model="form.type" @change="handleTypeChange" class="form-radio-group">
            <el-radio label="text">文本</el-radio>
            <el-radio label="num">数字</el-radio>
            <el-radio label="option">选项</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="同级顺序" prop="tseq" class="form-item">
          <el-input-number v-model="form.tseq" placeholder="请输入同级顺序" min="1" class="form-input-number"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark" class="form-item">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" class="form-textarea" rows="3"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" class="dialog-btn submit-btn" @click="submitForm">确 定</el-button>
        <el-button class="dialog-btn cancel-btn" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listInd, getInd, delInd, addInd, updateInd} from "@/api/data/indicator";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Indicator",
  components: {
    Treeselect
  },
  data() {
    return {
      loading: true,
      showSearch: true,
      indicatorList: [],
      indicatorOptions: [],
      title: "",
      open: false,
      isExpandAll: true,
      refreshTable: true,
      queryParams: {
        cond: null,
        orderByColumn: 'tseq',
        isAsc: 'desc'
      },
      form: {},
      options: [''],
      rules: {
        name: [
          {required: true, message: "名称不能为空", trigger: "blur"}
        ],
        code: [
          {required: true, message: "编码不能为空", trigger: "blur"}
        ],
        isdir: [
          {required: true, message: "请选择是否为目录", trigger: "change"}
        ],
        type: [
          {required: true, message: "请选择需求类型", trigger: "change"}
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      listInd(this.queryParams).then(response => {
        this.indicatorList = this.handleTree(response.data, "id", "pid");
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    rowClassName({row}) {
      let classes = 'tree-row';
      if (row.isdir === 'Y') {
        classes += ' parent-node';
      }
      return classes;
    },
    getTreeselect() {
      listInd().then(res => {
        this.indicatorOptions = [];
        const data = { id: "0", name: "顶级节点", children: [] };

        // 过滤掉非目录节点，只保留 isdir='Y' 的节点
        const filteredData = res.data.filter(item => item.isdir === 'Y');

        data.children = this.handleTree(filteredData, "id", "pid");
        this.indicatorOptions.push(data);
      });
    },
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleQuery() {
      this.getList();
    },
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.id) {
        this.form.pid = row.id;
      } else {
        this.form.pid = "0";
      }
      this.open = true;
      this.title = "添加指标";
      this.$nextTick(() => {
        this.$refs.code.focus();
      });
    },
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form = JSON.parse(JSON.stringify(row));
        if (this.form.isdir === 'N') {
          if (!this.form.type) {
            this.form.type = 'text';
          }
          if (this.form.type === 'option' && this.form.options) {
            this.options = this.form.options.split(';');
          }
        }
      }
      this.open = true;
      this.title = "修改指标";
      this.$nextTick(() => {
        this.$refs.code.focus();
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          try {
            const submitData = JSON.parse(JSON.stringify(this.form));
            if (submitData.type === 'option' && this.options) {
              submitData.options = this.options.filter(opt => opt.trim()).join(';');
            }
            if (this.form.id != null) {
              updateInd(submitData).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addInd(submitData).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          } catch (error) {
            console.error('提交表单时发生错误:', error);
            this.$message.error('提交表单时发生错误，请检查数据格式');
          }
        }
      });
    },
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.name + '"的数据项?').then(function() {
        return delInd(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    reset() {
      this.form = {
        pid: undefined,
        name: undefined,
        code: undefined,
        isdir: 'Y',
        type: 'text',
        text: '',
        options: '',
        tseq: 10,
        remark: undefined
      };
      this.options = [''];
      this.resetForm("form");
    },
    handleIsdirChange(val) {
      if (val === 'Y') {
        this.form.type = null;
        this.form.text = null;
        this.form.options = null;
        this.options = [''];
      } else {
        this.form.type = 'text';
      }
    },
    handleTypeChange(type) {
      if (type === 'text') {
        this.form.options = '';
      } else if (type === 'num') {
        this.form.text = '';
        this.form.options = '';
      } else if (type === 'option') {
        this.form.text = '';
        this.options = [''];
      }
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    addOption() {
      this.options.push('');
    },
    removeOption(index) {
      this.options.splice(index, 1);
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  background-color: #fafbfc;
  border-radius: 4px;
  padding: 20px 24px;
  box-shadow: 0 1px 8px rgba(0, 0, 0, 0.03);
}

::v-deep .el-form {
  background-color: #fff;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 20px;
  border: 1px solid #ebeef5;

  .el-input__inner {
    border-radius: 3px;
    transition: all 0.2s;
  }

  .el-form-item {
    margin-bottom: 0;
  }
}

.mb8 {
  margin-bottom: 18px;
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 12px 16px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.action-button, .search-btn, .reset-btn, .dialog-btn {
  border-radius: 3px;
  transition: all 0.2s;
  font-weight: 400;
  font-size: 12px;
  padding: 8px 15px;

  i {
    margin-right: 4px;
  }
}

.add-btn, .search-btn {
  background-color: #0960bd;
  border: 1px solid #0960bd;
  color: #fff;

  &:hover {
    background-color: #0854a9;
    border-color: #0854a9;
  }
}

.expand-btn, .reset-btn, .cancel-btn {
  background-color: #f2f3f5;
  border: 1px solid #dcdfe6;
  color: #606266;

  &:hover, &:focus {
    background-color: #e9ebef;
    color: #333;
  }
}

.submit-btn {
  background-color: #0960bd;
  border-color: #0960bd;
  color: #fff;
  margin-right: 12px;

  &:hover {
    background-color: #0854a9;
    border-color: #0854a9;
  }
}

.tree-table {
  margin-top: 15px;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #ebeef5;
}

.tree-node-name {
  display: inline-flex !important;
  align-items: center;

  .node-icon {
    margin-right: 8px;
    font-size: 16px;

    &.el-icon-folder {
      color: #E6A23C;
    }

    &.el-icon-document {
      color: #409EFF;
    }
  }
}

.table-operation {
  display: flex;
  justify-content: center;
  align-items: center;

  .link-text {
    font-size: 13px;
    text-decoration: none;
    cursor: pointer;
    padding: 2px 4px;

    i {
      margin-right: 2px;
      font-size: 12px;
    }
  }

  .link-divider {
    margin: 0 5px;
    color: #DCDFE6;
  }

  .empty-placeholder {
    width: 45px;
    display: inline-block;
  }

  .edit-link {
    color: #409EFF;
  }

  .add-link {
    color: #18a058;
  }

  .delete-link {
    color: #d03050;
  }
}

.option-list {
  max-height: 300px;
  overflow-y: auto;
  padding: 5px 0;
}

.option-item {
  padding: 8px 10px;
  border-bottom: 1px dashed #eee;
  display: flex;
  align-items: flex-start;

  &:last-child {
    border-bottom: none;
  }
}

.option-index {
  min-width: 25px;
  color: #909399;
  font-weight: bold;
}

.option-text {
  flex: 1;
}

.ind-form {
  .form-item {
    margin-bottom: 22px;
  }

  .form-input, .form-textarea, .tree-select, .form-input-number {
    width: 100%;
  }

  .form-radio-group {
    display: flex;
    line-height: 32px;
  }

  .type-selector {
    margin-bottom: 25px;
    padding-bottom: 15px;
    border-bottom: 1px dashed #EBEEF5;
  }
}

.dialog-footer {
  text-align: right;
  padding-top: 10px;
}
</style>


